// 混入 - 公共
import constant from "@/static/utils/constant.js";
export default {
	data() {
		return {
			$const: constant,
			token: uni.getStorageSync("token"),
			userInfo: uni.getStorageSync("userInfo") || {},

			// 分页信息
			page: {
				total: 0,
				pageSize: 20,
				curPage: 1,
			},
		}
	},
	onLoad(e) {},
	onShow() {
		this.checkOpenId();
		this.token = uni.getStorageSync("token");
		this.userInfo = uni.getStorageSync("userInfo") || {};
	},
	methods: {
		// 检查openid和sessionKey
		checkOpenId() {
			let openid = uni.getStorageSync("openid");
			let sessionKey = uni.getStorageSync("sessionKey");
			if (!openid || !sessionKey) {
				console.log('session_key 尚未获取，需要重新获取');
				this.getUserOpenId();
				return;
			}
			wx.checkSession({
				success: () => {
					console.log('session_key 未过期，并且在本生命周期一直有效');
				},
				fail: () => {
					console.log('session_key 已经失效，需要重新执行登录流程');
					this.getUserOpenId();
					return;
				}
			})
		},
		// 获取用户openid和sessionKey
		getUserOpenId() {
			var that = this
			uni.login({
				success: res => {
					// 发送 res.code 到后台换取 openId, sessionKey
					if (res.code) {
						this.$request.getOpenId({
							code: res.code,
							isLoading: false,
						}, (res) => {
							uni.setStorageSync("openid", res.openid)
							uni.setStorageSync("sessionKey", res.session_key)
							// that.saveUserOpenId(res.openid);
						})
					} else {
						console.log('登录失败！' + res.errMsg);
					}
				}
			});
		},
		// 保存用户openid
		saveUserOpenId(openid) {
			let token = uni.getStorageSync("token");
			if (!this.$utils.isNull(token)) {
				var params = {
					openid: openid,
					token: token,
					isLoading: false,
				};
				this.$request.saveUserInfo(params, (res) => {})
			}
		},
		// 页面跳转小方法
		toPath(url) {
			uni.navigateTo({
				url: `${url}`
			});
		},
	},
	computed: {},
}